<?php

namespace app\common\model\xiluhouse;

use think\Model;

class RentalTag extends Base
{

    // 表名
    protected $name = 'xiluhouse_rental_tag';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public function tagType(){
        return $this->belongsTo(HouseTagType::class,'tag_type_id','id',[],'inner')->setEagerlyType(0);
    }

    public function tag(){
        return $this->belongsTo(HouseTag::class,'tag_id','id',[],'inner')->setEagerlyType(0);
    }

    /**
     * 关联经纪人
     * @param $rental
     * @param $broker_user_ids
     * @param string $type
     * @return array|bool|false|\think\Collection|\think\model\Collection
     * @throws \think\Exception
     */
    public static function setTagIds($rental,$tags,$type='add'){
        if($type == 'add'){
            $insertTagIds = [];
            foreach ($tags as $tag_type_id => $tag){
                $tag_ids = explode(',',$tag);
                foreach ($tag_ids as $tag_id){
                    $insertTagIds[] = ['rental_id'=>$rental->id,'tag_type_id'=>$tag_type_id,'tag_id'=>$tag_id];

                }
            }
            return (new self())->saveAll($insertTagIds);
        }else{
            if($tags) {
                $ids = [];
                foreach ($tags as $tag_type_id => $tag){
                    $tag_ids = explode(',',$tag);
                    foreach ($tag_ids as $tag_id){
                        $insertTagId = ['rental_id'=>$rental->id,'tag_type_id'=>$tag_type_id,'tag_id'=>$tag_id];
                        $row = self::where('rental_id',$rental->id)->where('tag_type_id',$tag_type_id)->where('tag_id',$tag_id)->find();
                        if($row){
                            $ids[] = $row->id;
                            $row->save($insertTagId);
                        }else{
                            $result = self::create($insertTagId);
                            $ids[] = $result->id;
                        }

                    }
                }
                if($ids) {
                    return (new self())->where('rental_id',$rental->id)->whereNotIn('id',$ids)->delete();
                }
            }else {
                self::where('rental_id', $rental->id)->delete();
            }
        }
    }

}
